package com.app.sanyou.view.data;

import android.app.Activity;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.app.sanyou.R;
import com.app.sanyou.common.CallListener;
import com.app.sanyou.common.JsonResult;
import com.app.sanyou.constants.Request;
import com.app.sanyou.entity.Equipment;
import com.app.sanyou.entity.FactoryVo;
import com.app.sanyou.utils.DateUtils;
import com.app.sanyou.utils.HttpUtil;
import com.app.sanyou.utils.JsonUtil;
import com.app.sanyou.utils.StringUtil;
import com.app.sanyou.utils.UserUtil;
import com.app.sanyou.view.login.LoginActivity;
import com.app.sanyou.view.viewpager.EchartView;
import com.borax12.materialdaterangepicker.date.DatePickerDialog;
import com.google.gson.Gson;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class CooperActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener {

    private static final String TAG = "CooperActivity";
    private EchartView chart;

    private Spinner echartsSpinner;
    private Spinner equipmentsSpinner;
    private LinearLayout llFactory;
    private Spinner factoriesSpinner;
    private Spinner subfactoriesSpinner;
    private TextView dateText;
    private Button searchBtn;

    private ImageView back_img;
    private TextView back_text;
    private TextView title_text;

    private Context context;
    private FragmentManager fragmentManager;

    private String userId;
    /**
     * 实时数据  历史数据  周期数据  正太分布
     */
    private String chartType;
    private final String cooperPrefix="铜粒子";
    private String equipmentNo;
    private String subFactoryNo;
    private Date startTime;
    private Date endTime;

    //private List<IndustryDataVo> chartDataList;
    private String chartDataJson;

    private Handler handler = new Handler();

    /*public static DataActivity getInstance(Context context, FragmentManager fragmentManager){
        DataActivity dataFragment = new DataActivity();
        dataFragment.context = context;
        dataFragment.fragmentManager = fragmentManager;
        return dataFragment;
    }*/

    private CallListener equipmentListener = new CallListener() {

        Gson gson = new Gson();

        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void success(JsonResult result) {
            List<Equipment> equipmentList = JsonUtil.jsonToList(result.getData(), Equipment[].class);
            String[] equipments = equipmentList.stream().map(t -> t.getEquipNo()).collect(Collectors.toList()).toArray(new String[0]);

            ArrayAdapter<String> adapter = new ArrayAdapter<>(context, R.layout.support_simple_spinner_dropdown_item, equipments);
            handler.post(() -> {
                equipmentsSpinner.setAdapter(adapter);
            });
        }

        @Override
        public void failure(JsonResult result) {
            Log.d(TAG, "failure: " + gson.toJson(result));
            CooperActivity.this.runOnUiThread(()->Toast.makeText(context,result.getMsg(),Toast.LENGTH_SHORT).show());
        }
    };

    //请求全部工厂的接口回调函数
    private CallListener factoryListener = new CallListener() {

        Gson gson = new Gson();

        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void success(JsonResult result) {
            List<FactoryVo> factoryVoList = JsonUtil.jsonToList(result.getData(), FactoryVo[].class);
            //String[] factories = factoryVoList.stream().map(t -> t.getId()).collect(Collectors.toList()).toArray(new String[0]);

            ArrayAdapter<FactoryVo> adapter = new ArrayAdapter<>(context
                    , R.layout.support_simple_spinner_dropdown_item, factoryVoList);
            handler.post(() -> {
                factoriesSpinner.setAdapter(adapter);
            });
        }

        @Override
        public void failure(JsonResult result) {
            Log.d(TAG, "failure: " + gson.toJson(result));
            CooperActivity.this.runOnUiThread(()->Toast.makeText(context,result.getMsg()
                    ,Toast.LENGTH_SHORT).show());
        }
    };
    //请求全部车间的接口回调函数
    private CallListener subfactoryListener = new CallListener() {

        Gson gson = new Gson();

        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void success(JsonResult result) {
            List<FactoryVo> subfactoryVoList = JsonUtil.jsonToList(result.getData()
                    , FactoryVo[].class);
            //String[] factories = subfactoryVoList.stream().map(t -> t.getId()).collect(Collectors.toList()).toArray(new String[0]);

            ArrayAdapter<FactoryVo> adapter = new ArrayAdapter<>(context
                    , R.layout.support_simple_spinner_dropdown_item, subfactoryVoList);
            handler.post(() -> {
                subfactoriesSpinner.setAdapter(adapter);
            });
        }

        @Override
        public void failure(JsonResult result) {
            Log.d(TAG, "failure: " + gson.toJson(result));
            CooperActivity.this.runOnUiThread(()->Toast.makeText(context,result.getMsg()
                    ,Toast.LENGTH_SHORT).show());
        }
    };

    private CallListener echartsListener = new CallListener() {

        Gson gson = new Gson();

        @Override
        public void success(JsonResult result) {
            Log.d(TAG, "success: " + gson.toJson(result));
            //chartDataList = JsonUtil.jsonToList(result.getData(),IndustryDataVo[].class);
            chartDataJson = gson.toJson(result.getData());
            handler.post(() -> refreshChart(chartType));
        }

        @Override
        public void failure(JsonResult result) {
            Log.d(TAG, "failure: " + gson.toJson(result));
        }
    };


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cooper);
        context=this;
        fragmentManager = getFragmentManager();
        //初始化view
        initView(this);
        initClickListener();

        //判断用户登录是否过期
        userId = UserUtil.getUserId(context);
        if(StringUtil.isNull(userId)){
            UserUtil.loginOut(context);
            Intent intent = new Intent(context, LoginActivity.class);
            startActivity(intent);
        }

        //加载用户拥有权限的铜粒子设备数据
        HttpUtil.get(Request.URL + "/equipment/getUserEquip?equipType=1&userId=" + userId
                ,equipmentListener);

        //加载工厂选择
        HttpUtil.get(Request.URL + "/factory/getFactory?userId=" + userId,factoryListener);


        chart.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }
        });

    }

    private void initView(Activity activity){
        echartsSpinner = activity.findViewById(R.id.echarts_spinner);
        equipmentsSpinner = activity.findViewById(R.id.equipments_spinner);
        llFactory = activity.findViewById(R.id.ll_factory);
        factoriesSpinner = activity.findViewById(R.id.factory_spinner);
        subfactoriesSpinner = activity.findViewById(R.id.subfactory_spinner);
        dateText = activity.findViewById(R.id.date_text);
        searchBtn = activity.findViewById(R.id.search_btn);
        chart = activity.findViewById(R.id.chart);

        //初始化顶部栏
        back_img = activity.findViewById(R.id.back_img);
        back_text = activity.findViewById(R.id.back_text);
        title_text = activity.findViewById(R.id.title_text);
        title_text.setText("数据中心");
    }

    private void initClickListener() {
        //返回
        back_img.setOnClickListener(v-> finish());
        back_text.setOnClickListener(v-> finish());
        dateText.setOnClickListener(v -> {
            Calendar calendar = Calendar.getInstance();
            DatePickerDialog datePickerDialog = DatePickerDialog.newInstance(this,
                    calendar.get(Calendar.YEAR),
                    calendar.get(Calendar.MONTH),
                    calendar.get(Calendar.DAY_OF_MONTH));
            datePickerDialog.show(fragmentManager, "Datepickerdialog");
            //datePickerDialog.show();
        });

        //
        echartsSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                //实时数据是根据设备类型来的
                String selectedType=echartsSpinner.getSelectedItem().toString();
                if (selectedType.equals("实时数据")) {
                    llFactory.setVisibility(View.GONE);
                    equipmentsSpinner.setVisibility(View.VISIBLE);
                }
                else {
                    //其他是根据车间id来的
                    llFactory.setVisibility(View.VISIBLE);
                    equipmentsSpinner.setVisibility(View.GONE);
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) { }
        });
        //选择工厂后的点击事件
        factoriesSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                //请求相应的车间信息
                String factoryId=((FactoryVo) factoriesSpinner.getSelectedItem()).getId();
                //加载车间选择
                HttpUtil.get(Request.URL + "/factory/getSubFactory?userId=" + userId
                        + "&factoryId=" + factoryId,subfactoryListener);
            }
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) { }
        });

        searchBtn.setOnClickListener(v -> {
            chartType = cooperPrefix + echartsSpinner.getSelectedItem().toString();
            equipmentNo = equipmentsSpinner.getSelectedItem().toString();
            FactoryVo subFactory = (FactoryVo) subfactoriesSpinner.getSelectedItem();

            if(!chartType.equals(cooperPrefix+"实时数据")){
                if(subFactory == null){
                    Toast.makeText(context,"请选择工厂!",Toast.LENGTH_SHORT).show();
                    return;
                }else {
                    //Log.d(TAG,subFactory.toString()+subFactory.getId());
                    subFactoryNo = subFactory.getId();
                }
            }
            if(startTime == null || endTime == null){
                Toast.makeText(context,"请选择日期!",Toast.LENGTH_SHORT).show();
            }else{
                Map<String,String> postData = new HashMap<>();
                postData.put("deviceNo",equipmentNo);
                postData.put("subFactoryNo",subFactoryNo);
                postData.put("interval","1");//?
                postData.put("userId",userId);

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                postData.put("startTime",sdf.format(startTime));
                postData.put("startDate",sdfDate.format(startTime));//"yyyy-MM-dd HH:mm:ss"
                postData.put("endTime",sdf.format(endTime));
                postData.put("endDate",sdfDate.format(endTime));//"yyyy-MM-dd HH:mm:ss"
                Gson gson = new Gson();
                String json = gson.toJson(postData);

                String url = "";
                if((cooperPrefix+"实时数据").equals(chartType)){
                    url = "/copper/copperPieRtData";
                }else if((cooperPrefix+"历史数据").equals(chartType)){
                    url = "/copper/copperHistoryData";
                }
                //铜粒子无该需求
                /*else if((cooperPrefix+"周期数据").equals(chartType)){
                    url = "/copper/copperHistoryData";//无需
                }else if((cooperPrefix+"正太分布").equals(chartType)){
                    url = "/copper/copperHistoryData";//无需
                }*/
                HttpUtil.post(Request.URL + url, json, echartsListener);
            }
        });
    }

    private void refreshChart(String chartType){
        Gson gson = new Gson();

        if((cooperPrefix+"实时数据").equals(chartType)){
            if(chartDataJson==null)
                return;

            String json = chartDataJson;

            chart.refreshEchartsWithOption(chartType,json);
        }else if((cooperPrefix+"历史数据").equals(chartType)){
            if(chartDataJson == null)
                return;

            String json = chartDataJson;
            chart.refreshEchartsWithOption(chartType,json);
        }
        //铜粒子无该需求
        /*else if((cooperPrefix+"周期数据").equals(chartType)){
            if(chartDataJson == null)
                return;

            String json = chartDataJson;
            chart.refreshEchartsWithOption(chartType,json);
        }else if((cooperPrefix+"正太分布").equals(chartType)){
            if(chartDataJson == null)
                return;

            String json = chartDataJson;
            chart.refreshEchartsWithOption(chartType,json);
        }*/
    }


    @Override
    public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth
            , int yearEnd, int monthOfYearEnd, int dayOfMonthEnd) {
        Calendar startCalendar = new GregorianCalendar(year,monthOfYear,dayOfMonth);
        startTime = startCalendar.getTime();
        Calendar endCalendar = new GregorianCalendar(yearEnd,monthOfYearEnd,dayOfMonthEnd);
        endTime = endCalendar.getTime();

        //开始时间的时间戳
        String timeStart = DateUtils.getTimeStart("" + year + "年" + (monthOfYear + 1)
                + "月" + dayOfMonth + "日");
        //结束时间的时间戳
        String timeEnd = DateUtils.getTimeEnd("" + yearEnd + "年" + (monthOfYearEnd + 1)
                + "月" + dayOfMonthEnd + "日");

        String dateStr = year + "年" + (monthOfYear + 1) + "月" + dayOfMonth + "日" + " - " +
                yearEnd + "年" + (monthOfYearEnd + 1) + "月" + dayOfMonthEnd + "日";

        dateText.setText(dateStr);

        try {
            if (Long.parseLong(timeStart) > Long.parseLong(timeEnd)) {
                Toast.makeText(context, "结束时间不能小于开始时间", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Toast.makeText(context, "选择时间的有误", Toast.LENGTH_SHORT).show();
        }
    }
}
